<template>
  <div class="addRole">
    <div class="box" @click="$event.stopPropagation()">
      <div class="title">
        <h3>添加角色</h3>
        <el-icon @click="fn"><Close /></el-icon>
      </div>
      <div class="inp">
        <el-form ref="formRef" :model="userForm" :rules="rules">
          <el-form-item prop="roleName" label="角色名称">
            <el-input v-model="userForm.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item prop="roleDesc" label="角色描述">
            <el-input v-model="userForm.roleDesc" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="but">
        <el-button @click="callOff">取消</el-button>
        <el-button type="primary" @click="ensure">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Close } from '@element-plus/icons-vue'
import { useCounterStoreB } from '@/stores/temporary'
import { addRole } from '@/api/addRole'
const storeB = useCounterStoreB()
const addState = ref(storeB.addState)
const formRef = ref()
const userForm = reactive({
  roleName: '',
  roleDesc: '',
})
const rules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
  ],
  roleDesc: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
  ],
})
const fn = () => {
  addState.value = !addState.value
  storeB.stateFun(addState.value)
}
const callOff = () => {
  fn()
  userForm.roleName = ''
  userForm.roleDesc = ''
}
const ensure = async () => {
  fn()
  try {
    await addRole({ ...userForm })
  } catch (error) {
    console.log(error)
  }
}
watch(
  () => storeB.addState,
  (i) => {
    addState.value = i
  },
)
</script>

<style scoped lang="scss">
.box {
  width: 50vw;
  background: #fff;
  padding: 10px;
  display: flex;
  flex-direction: column;
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    h3 {
      margin: 0px;
    }
  }
  .inp {
    margin: 10px 0px;
  }
  .but {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
